// https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
$(document).ready(function () {
  // open database
  var request = indexedDB.open('customermanager', 1)

  // vai aumentar o numero da versao quando alterado algun valor
  request.onupgradeneeded = function (e) {
    var db = e.target.result

    if (!db.objectStoreNames.contains('customers')) {
      var os = db.createObjectStore('customers', { keyPath: "id", autoIncrement: true })
      // Create Index for Name
      os.createIndex('name', 'name', { unique: false })
    }

  }

  // Generating handlers - error ou sucess
  // success
  request.onsuccess = function (e) {
    console.log('Success: Opened Database....')
    db = e.target.result
    // show customers - chama a funçao
    showCustomers()
  }

  // Error
  request.onerror = function () {
    console.log('Error: Não possivel abrir o banco de dados....')
  }

})

// add customer
function addCustomer() {
  var name = $('#name').val()
  var email = $('#email').val()

  var transaction = db.transaction(["customers"], "readwrite")
  // ask for objectStore
  var store = transaction.objectStore('customers')

  // define customer
  var customer = {
    name: name,
    email: email
  }

  // perform the add
  var request = store.add(customer)

  // success
  request.onsuccess = function (e) {
    window.location.href = "index.html"
  }

  // error
  request.onerror = function (e) {
    alert('Sorry, the customer was not added')
    console.log('Error', e.target.error.name)
  }

}


// show customers
function showCustomers(e) {
  var transaction = db.transaction(["customers"], "readonly")
  // ask for objectStore
  var store = transaction.objectStore('customers')
  var index = store.index('name')

  // constuindo a saida

  var output = ''
  index.openCursor().onsuccess = function (e) {
    var cursor = e.target.result
    if (cursor) {
      output += "<tr id='customer_" + cursor.value.id + "'>"
      output += "<td>" + cursor.value.id + "</td>"
      output += "<td><span class='cursor customer' contenteditable='true' data-field='name' data-id='" + cursor.value.id + "'>" + cursor.value.name + "</span></td>"
      output += "<td><span class='cursor customer' contenteditable='true' data-field='email' data-id='" + cursor.value.id + "'>" + cursor.value.email + "</span></td>"
      output += "<td><a onclick='removeCustomer(" + cursor.value.id + ")' href=''>Delete</a></td>"
      output += "</tr>"
      cursor.continue()
    }
    $('#customers').html(output)
  }

}

// delete um customers
function removeCustomer(id) {
  var transaction = db.transaction(["customers"], "readwrite")
  // ask for objectStore
  var store = transaction.objectStore('customers')

  var request = store.delete(id)

  // success
  request.onsuccess = function () {
    console.log('Customer ' + id + ' Deleted')
    $('.customer_' + id).remove()
  }

  // error
  request.onerror = function (e) {
    alert('Sorry, the customer was not removed')
    console.log('Error', e.target.error.name)
  }

}

// delete todos customers
function clearCustomers() {
  indexedDB.deleteDatabase('customermanager')
  window.location.href = "index.html"
}


// update customers
// quando clicar, editar e sair = blur event
$('#customers').on('blur', '.customer', function () {
  // newly entered text
  var newText = $(this).html()
  // field 
  var field = $(this).data('field') // data-field
  // customer id
  var id = $(this).data('id') // data-id

  // get transation para fazer o update
  var transaction = db.transaction(["customers"], "readwrite")
  // ask for objectStore
  var store = transaction.objectStore('customers')

  // vai pegar o id que foi atualizado
  var request = store.get(id)
  // se tiver sucesso de pegar o id (assim ele existe) vai atualizar com novo valor
  request.onsuccess = function () {
    var data = request.result
    if (field == 'name') {
      data.name = newText
    } else if (field == 'email') {
      data.email = newText
    }

    // store updated text
    var requestUpdate = store.put(data)

    requestUpdate.onsuccess = function () {
      console.log('Customer field Updated..')
    }

    requestUpdate.onerror = function () {
      console.log('Customer field NOT Updated..')
    }

  }
})